package com.example.criminalintent.view

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.DatePicker
import androidx.fragment.app.DialogFragment
import com.example.criminalintent.R
import java.util.*

class DatePickerFragment : DialogFragment() {

    @SuppressLint("InflateParams")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val date = arguments!!.getSerializable(ARG_DATE) as Date

        val instance = Calendar.getInstance()
        instance.time = date
        val view = LayoutInflater.from(activity).inflate(R.layout.dialog_date, null)
        val datePicker = view.findViewById<DatePicker>(R.id.dialog_date_picker)
        datePicker.init(
            instance[Calendar.YEAR],
            instance[Calendar.MONTH],
            instance[Calendar.DAY_OF_MONTH],
            null
        )
        return AlertDialog.Builder(activity).setView(view).setTitle(R.string.date_picker_title)
            .setPositiveButton(
                android.R.string.ok
            ) { _, _ ->
                sendResult(
                    Activity.RESULT_OK,
                    GregorianCalendar(datePicker.year, datePicker.month, datePicker.dayOfMonth).time
                )
            }.create()
    }

    companion object {
        const val ARG_DATE = "date"
        const val EXTRA_DATE = "com.example.criminalintent.date"

        fun newInstance(date: Date): DialogFragment {
            val bundle = Bundle()
            bundle.putSerializable(ARG_DATE, date)
            val datePickerFragment = DatePickerFragment()
            datePickerFragment.arguments = bundle
            return datePickerFragment
        }
    }

    private fun sendResult(resultCode: Int, date: Date) {
        if (targetFragment == null)
            return
        val intent = Intent()
        intent.putExtra(EXTRA_DATE, date)
        targetFragment!!.onActivityResult(targetRequestCode, resultCode, intent)
    }
}